package com.ynu.springbootappdemo.service;

import com.ynu.springbootappdemo.dao.IDeliveryAddressDao;
import com.ynu.springbootappdemo.dao.IOrderDao;
import com.ynu.springbootappdemo.dao.ISkuItemDao;
import com.ynu.springbootappdemo.model.dto.orders.SaveOrderDTO;
import com.ynu.springbootappdemo.model.dto.orders.SaveOrderDetailsDTO;
import com.ynu.springbootappdemo.model.dto.orders.UpdateOrderStateDTO;
import com.ynu.springbootappdemo.model.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.ynu.springbootappdemo.common.constant.CommonConstant.ORDER_STATE_UNPAID;

@Service
@Slf4j
public class OrderService {
    @Resource
    private IOrderDao dao;

    @Resource
    private ISkuItemDao skuDao;

    @Resource
    private IDeliveryAddressDao deliveryAddressDao;

    @Resource
    private UserService userService;

    public List<Orders> getAllOrders(HttpServletRequest request){
        return dao.findAllByCustomer(userService.getLoginUser(request));
    }
    public Orders getById(Long id,HttpServletRequest request){
        return dao.findAllByCustomerAndId(userService.getLoginUser(request),id);
    }


    public Orders updateState(UpdateOrderStateDTO dto,HttpServletRequest request){
        Orders orders = dao.findAllByCustomerAndId(userService.getLoginUser(request), dto.getId());
        orders.setOrderState(dto.getState());
        return dao.save(orders);
    }

    public Orders saveOrder(SaveOrderDTO dto, HttpServletRequest request){
        //获取登录用户
        User loginUser = userService.getLoginUser(request);
        //新建订单
        Orders orders = new Orders();
        orders.setCustomer((Customer) loginUser);
        orders.setOrderRemark(dto.getOrderRemark());
        orders.setDeliveryTime(dto.getDeliveryTime());
        orders.setOrderState(ORDER_STATE_UNPAID);
        //获取收货地址
        DeliveryAddress address = deliveryAddressDao.findDeliveryAddressByCustomerAndId(loginUser, dto.getAddressId());
        orders.setDeliveryAddress(address);
        //创建订单细则
        double total = 0;
        Set<OrderDetail> orderDetails = new HashSet<>();
        for (SaveOrderDetailsDTO cartItem : dto.getOrderItems()) {
            //新建订单细则
            OrderDetail orderDetail = new OrderDetail();
            SkuItem item = skuDao.getReferenceById(cartItem.getSkuId());
            orderDetail.setQuantity(cartItem.getQuantity());
            orderDetail.setSkuItem(item);
            //计算金额
            total += cartItem.getQuantity() * item.getGoods().getPrice();
            orderDetails.add(orderDetail);
        }
        //设置订单金额
        orders.setOrderAmount(total);
        orders.setOrderDetails(orderDetails);
        return dao.save(orders);
    }
}
